#!/usr/bin/perl -w

BEGIN   {
	sub getPoints{return '../../' if (!$_[1]);return '../' if (!$_[0]);return '/';}
	(my $file = __FILE__) =~ s/(\/?modules)?(\/?http_logging)?\/?\w+\.pl$/&getPoints($1,$2)/e;
	unshift(@INC, $file.'bin');
	unshift(@INC, $file.'modules/http_logging');
}

use strict;
use TWM;
use Logging;


my @isp = split(/\|{1,3}/, $ck{ifaces});
my $server_ip = $isp[2];
my $server_info = getIPInfo($isp[2]);
if (!$server_info)
{
	logModuleError("Could not find host by ip '$server_ip'. Please check TrafficPanel configuration, variable 'Interfaces'");
	exit;
}
my $server_name = $server_info->{'dns_name'}.".".$ck{'_domain_name'};
(my $enddt = getTaskEndDt('http_logging','parsing')) =~ s/\:\d\d$//;

my $dt4mail = `$ck{date} +%H:%M`;
my $dt = `$ck{date} +%Y%b%d`;
my $sarg_dt = `$ck{date} +%d/%m/%Y`;
chomp($dt4mail,$dt,$sarg_dt);

my $logging = new Logging;
my $squid_settings = $logging->getSquidsSettings();

my $is_sarg_running = `$ck{ps} ax|$ck{grep} -v 'grep'|$ck{grep} -c $cm{sarg}`;
chomp $is_sarg_running;
if ($is_sarg_running ne '0') { print "Running sarg process has been found. script terminated.\n"; exit 0 }

foreach my $v (values %$squid_settings)	{

	my (@content4print,@content4mail,@ips);
	my $log_folder = $v->{log_folder};
	my $access_log = $v->{access_log};
	my $isp = $v->{isp};
	my $enabled = $v->{enabled};

	if ($enabled) {

	system "$ck{nice} -n 19 $cm{sarg} -n -d $sarg_dt -l $log_folder/$access_log -o $ck{twmfolder}modules/$mc/logs/$isp -f $cm{sarg_conf} > $cm{sarg_log}";

	my $index_file="$ck{twmfolder}modules/$mc/logs/$isp/$dt-$dt/index.html";

	if (-e $index_file)	{

	local $/ = '';

	open(FILE, "+<$index_file") || toErrorLog("Can't open $index_file: $!", 1);
	my $f = <FILE>;

	$f =~ s/^<tr><th class="logo">.+Topuser Report<\/td><\/tr>\n<\/table><\/center>$//ms;
	$f =~ s/(?<=^<center><table cellpadding="1" cellspacing="2">\n)<tr><td><br><\/td><td><\/td><\/tr>.+Downloads.+Report.+\n<tr><td><\/td><\/tr>$//ms;
	$f =~ s/Generated by <a.+<\/a> on/Generated at/;

	@ips = ($f =~ /^.+=["'](\d{1,3}[._]\d{1,3}[._]\d{1,3}[._]\d{1,3})\/d.+$/mg);

	$f =~ s/(<img src=["'])../$1\/modules\/$mc/g;
	$f =~ s/<a href=["'](\d{1,3}[._]\d{1,3}[._]\d{1,3}[._]\d{1,3}\/graph_day\.png)["']>/<a href='sarg_img.pl?squid=$isp&dt=$dt&fl=$1'>/g;
	$f =~ s/<a href=["']((\w{6}|\w{8})\.html)["']>/<a href='sarg_rpt.pl?squid=$isp&dt=$dt&fl=$1'>/g;
	$f =~ s/<a href=["']\d{1,3}[._]\d{1,3}[._]\d{1,3}[._]\d{1,3}\/(d?\d{1,3}[._]\d{1,3}[._]\d{1,3}[._]\d{1,3})\.html["']>/<a href='sarg_rpt.pl?squid=$isp&dt=$dt&fl=$1'>/g;
	push (@content4print, $f);

#	$f =~ s/<a href=["']sarg_img.pl\?squid=$isp&dt=/<a href='http:\/\/$server_name:$ck{httpd_port}\/cgi-bin\/modules\/$mc\/sarg_img.pl\?squid=$isp&dt=/g;
#	$f =~ s/<a href=["']sarg_rpt.pl\?squid=$isp&dt=/<a href='http:\/\/$server_name:$ck{httpd_port}\/cgi-bin\/modules\/$mc\/sarg_rpt.pl\?squid=$isp&dt=/g;
#	$f =~ s/<a href=["']sarg_rpt.pl\?squid=$isp&dt=/<a href='http:\/\/$server_name:$ck{httpd_port}\/cgi-bin\/modules\/$mc\/sarg_rpt.pl\?squid=$isp&dt=/g;
	$f =~ s/<img src="\/modules\/http_logging\/images\//<img src="http:\/\/$server_name:$ck{httpd_port}\/modules\/http_logging\/images\//g;
	$f =~ s/<a href=["'](sarg_img.pl|sarg_rpt.pl)\?squid=$isp&dt=/<a href='http:\/\/$server_name:$ck{httpd_port}\/cgi-bin\/modules\/$mc\/$1\?squid=$isp&dt=/g;
	push (@content4mail, $f);

	seek(FILE,0,0) || toErrorLog("Seeking $index_file: $!",1);
	print FILE foreach @content4print;
	truncate(FILE, tell(FILE)) || toErrorLog("Truncating $index_file: $!",1);
	close(FILE) || toErrorLog("Can't close $index_file: $!",1);

	my $ip_list = &getIPs;

	foreach (@ips)	{

	my ($ip,$full_name) = ($_,'');
	$ip =~ s/_/./g;

	foreach (@$ip_list) {
	if ($_->{ip} eq $ip) {
   		$full_name = $_->{full_name};
		last;
		}
	}
	my $ipstring = "<tr><td class=\"header\" colspan=\"2\">ip:&nbsp;$ip</td></tr>\n";
{
	my @content4print;
	my $in="$ck{twmfolder}modules/$mc/logs/$isp/$dt-$dt/$_/$_\.html";
	open(FILE, "+<$in") || toErrorLog("Can't open $in: $!",1);
	my $f = <FILE>;
	$f =~ s/^[<>\w\s]+="logo">.+\n//m;
	$f =~ s/^[<>\s\w]+="title".+\n(.+\n[<>\s\w]+="header".+;)([\w\W]+?)(<.+\n).+\n.+\n.+\n/$1$2 \($full_name\)$3${ipstring}/mg;
	$f =~ s/Generated by <a.+<\/a> on/Generated at/;
	$f =~ s/(<img src=["'])..\/../$1\/modules\/$mc/g;
	$f =~ s/<a href=["'](tt.+\.html)["']>/<a href="sarg_rpt.pl?squid=$isp&dt=$dt&fl=$1">/g;
	push(@content4print,$f);
	seek(FILE,0,0) || toErrorLog("Seeking $in: $!",1);
	print FILE foreach @content4print;
	truncate(FILE, tell(FILE)) || toErrorLog("Truncating $in: $!",1);
	close(FILE) || toErrorLog("Can't close $in: $!",1);
}

{
	my @content4print;
	my $in="$ck{twmfolder}modules/$mc/logs/$isp/$dt-$dt/$_/d$_\.html";
	open(FILE, "+<$in") || toErrorLog("Can't open $in: $!",1);
	my $f = <FILE>;
	$f =~ s/^[<>\w\s]+="logo">.+\n//m;
	$f =~ s/.+\n[<>\w\s]+="title"\s.+\n.+\n//;
	$f =~ s/^(<.+>User\:.+?\;)([\d\.]+?)(<.+\n)/$1$full_name$3${ipstring}/m;
#	$f =~ s/^([<>\w\s"=]+User[^;]+?;)(\w+)(<.+\n)/$1$2$3${ipstring}/m;
	$f =~ s/$2/$full_name}/ if ($2);
	$f =~ s/Generated by <a.+<\/a> on/Generated at/;
	push(@content4print,$f);
	seek(FILE,0,0) || toErrorLog("Seeking $in: $!",1);
	print FILE foreach @content4print;
	truncate(FILE, tell(FILE)) || toErrorLog("Truncating $in: $!",1);
	close(FILE) || toErrorLog("Can't close $in: $!",1);
}

	my @ttlist = glob("$ck{twmfolder}modules/$mc/logs/$isp/$dt-$dt/$_/tt*.html");
	foreach(@ttlist) {
	my @content4print;
	open(FILE, "+<$_") || toErrorLog("Can't open $_: $!",1);
	my $f = <FILE>;
	$f =~ s/^[<>\w\s]+="logo">.+\n//m;
	$f =~ s/(?<=<table>\n)[<>\s\w]+="title".+\n(.+\n[<>\s\w]+="header".+;)([\w\W]+?)(<.+\n).+\n.+\n/$1${full_name}$3${ipstring}/m;
	push(@content4print,$f);
	seek(FILE,0,0) || toErrorLog("Seeking $_: $!",1);
	print FILE foreach @content4print;
	truncate(FILE, tell(FILE)) || toErrorLog("Truncating $_: $!",1);
	close(FILE) || toErrorLog("Can't close $_: $!",1);
	}

	}

	} 
	else {
		my $dt = $sarg_dt;
		$dt =~ s/\//\./g;
		push(@content4mail, "Hello<p>HTTP wasn't used by <b>$isp</b> ISP on $dt.");
	}

	toDebugLog("\$dt4mail:$dt4mail \$enddt:$enddt \$cm{email_last_log}:".$cm{email_last_log});

	if (($dt4mail eq $enddt) and ($cm{email_last_log}))	
	{
		my $report = join("",@content4mail)."\n";
		my $subj = $cm{subject};
		$subj =~ s/\[ISP\]/\[$isp\]/;
		toDebugLog("send report from: $ck{sender} , to: $cm{email_to}, size: ".length($report));
		send_email(
			{
				'from' => $ck{sender},
				'to' => $cm{email_to},
				'ctype' => 'text/html',
				'subject' => $subj,
				'body' => $report
			}
		);
	}

	}

}

__END__
